package com.block.datapush.service.apipush;

import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.crypto.digest.DigestUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.block.common.enums.ProfitSharingEnum;
import com.block.common.model.dto.ThirdInfoDTO;
import com.block.common.model.param.PushApiKeyParam;
import com.block.common.service.IApplicationInfoService;
import com.block.common.service.LogFactory;
import com.block.common.service.merchant.IMerchantThirdBaseInfoService;
import com.block.datapush.enums.PushStatusEnum;
import com.block.datapush.model.PushQueryParam;
import com.block.datapush.model.dto.NoticeParamDTO;
import com.block.datapush.model.result.ProtocolParamResult;
import com.block.datapush.model.result.PushApiResult;
import com.block.datapush.service.IPushApiService;
import com.block.datapush.service.apipush.utils.JinTongBaoUtil;
import com.block.datapush.service.apipush.utils.MobileMd5IsInListUtils;
import com.block.datapush.service.apipush.utils.XinXiaoRongUtil;
import com.block.db.entity.ApplicationInfo;
import com.block.db.entity.MemberSourceInfo;
import com.block.db.entity.MerchantBaseInfo;
import com.block.db.entity.MerchantDataPushInfo;
import com.block.db.mapper.MerchantDataPushInfoMapper;
import com.block.db.mapper.MerchantThirdBaseInfoMapper;
import org.apache.commons.codec.binary.Base64;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

/**
 *  金通宝双授权
 */
@Service
public class JinTongBaoApiService implements IPushApiService {

    private static final Logger log = LogFactory.getPushLog();

    @Autowired
    IMerchantThirdBaseInfoService merchantThirdBaseInfoService;
    @Autowired
    MerchantDataPushInfoMapper merchantDataPushInfoMapper;


    @Override
    public PushApiResult checkUser(String orderNo, PushApiKeyParam pushApiKeyParam, MemberSourceInfo memberSourceInfo, JSONObject extJson) throws Exception {

        PushApiResult pushApiResult = new PushApiResult();
        pushApiResult.setPushSuccess(false);
        long timestamp = System.currentTimeMillis();
        String timestamp1 = String.valueOf(timestamp);
        String queryUrl = pushApiKeyParam.getCheckUrl();
        String apiSecret = pushApiKeyParam.getApiSecret();
        HashMap<String, Object> paramMap = new HashMap<>();
        paramMap.put("mobileMask", memberSourceInfo.getMobile().substring(0,8));
        paramMap.put("ip", memberSourceInfo.getReqIp());
        paramMap.put("realname", memberSourceInfo.getRealname());
        paramMap.put("device", 1);
        paramMap.put("city",memberSourceInfo.getCity());
        paramMap.put("cityCode",memberSourceInfo.getCityCode());
        paramMap.put("age", memberSourceInfo.getAge());
        paramMap.put("sex", memberSourceInfo.getSex());
        paramMap.put("idCard", memberSourceInfo.getIdcard());
        paramMap.put("province", memberSourceInfo.getProvince());
        paramMap.put("provinceCode", memberSourceInfo.getProvinceCode());
        paramMap.put("loanAmount", memberSourceInfo.getLoanAmount());
        paramMap.put("huaBei", memberSourceInfo.getHuabei());
        paramMap.put("shebao", memberSourceInfo.getShebao());
        paramMap.put("baitiao", memberSourceInfo.getBaitiao());
        paramMap.put("yuqi", memberSourceInfo.getYuqi());
        paramMap.put("house", memberSourceInfo.getHouse());
        paramMap.put("loanTime", memberSourceInfo.getLoanTime());
        paramMap.put("baoxian", memberSourceInfo.getBaoxian());
        paramMap.put("xueli", memberSourceInfo.getXueli());
        paramMap.put("car", memberSourceInfo.getCar());
        paramMap.put("shouru", memberSourceInfo.getShouru());
        paramMap.put("gongzuo", memberSourceInfo.getGongzuo());
        paramMap.put("yongtu", memberSourceInfo.getYongtu());
        paramMap.put("weili", memberSourceInfo.getWeili());
        paramMap.put("xinyongka", memberSourceInfo.getXinyongka());
        paramMap.put("gjj", memberSourceInfo.getGjj());
        paramMap.put("zhima", memberSourceInfo.getZhima());

        String number = getNumber();
        String date = SecureUtil.aes(apiSecret.getBytes()).encryptBase64(JSON.toJSONString(paramMap));
        String s1 = date+"appId="+pushApiKeyParam.getApiCode()+"&nonce="+number+"&timestamp="+timestamp +apiSecret;
        Map<String, Object> aceMap = new HashMap<>();
        aceMap.put("data",date);


        SortedMap<String, String> headerMap = new TreeMap<>();
        headerMap.put("Content-Type", "application/json");
        headerMap.put("appId",pushApiKeyParam.getApiCode());
        headerMap.put("timestamp",timestamp1);
        headerMap.put("nonce",number);
        headerMap.put("sign",SecureUtil.md5(s1));

        String requestBody = JSON.toJSONString(aceMap);
        String signatureString = MapUtil.join(paramMap, "&", "=")
                + requestBody
                + MapUtil.join(headerMap, "&", "=")
                + apiSecret;
        headerMap.put("X-Signature", DigestUtil.sha256Hex(signatureString));

        log.info("【金通宝下游】撞库开始【queryUrl】{}【paramMap】{}【aceMap】{}", queryUrl, JSON.toJSONString(paramMap), JSON.toJSONString(aceMap));
        String result = HttpUtil.createPost(queryUrl)
                .addHeaders(headerMap)
                .body(requestBody)
                .execute().body();
        JSONObject resultObject = JSON.parseObject(result);

        log.info("【金通宝下游】撞库结束【result】{}", result);
        log.info("【金通宝下游】撞库结束【resultDes】{}", resultObject.toJSONString());

        Integer code = resultObject.getInteger("code");
        String msg = resultObject.getString("msg");

        pushApiResult.setCode(code + "|" + msg);
        pushApiResult.setMessage(msg);
        pushApiResult.setParamInfo(JSON.toJSONString(paramMap));
        pushApiResult.setResultInfo(result);

        if (StrUtil.equals(String.valueOf(code), "0")) {
            JSONObject data = resultObject.getJSONObject("data");
            String logo = data.getString("logo");
            String orderId = data.getString("orderId");
            String name = data.getString("name");
            String orgName = data.getString("orgName");
            // 撞库成功之后，商户的机构数据存储
            ThirdInfoDTO thirdInfoDTO = new ThirdInfoDTO();
            thirdInfoDTO.setInfoId(Integer.valueOf(pushApiKeyParam.getInfoId()));
            thirdInfoDTO.setInfoName(pushApiKeyParam.getInfoName());
            thirdInfoDTO.setOrderNo(orderNo);
            JSONObject infoObject = new JSONObject();
            infoObject.put("productName",name);
            infoObject.put("orderNo",orderId);
            infoObject.put("productId",orderId);
            infoObject.put("companyName",orgName);
            infoObject.put("companyLogo",logo);
            infoObject.put("maxLoanAmount","200000");
            infoObject.put("maxLoanRate","20");
            infoObject.put("minLoanRate","1");
            infoObject.put("businessInfo",pushApiKeyParam.getInfoName());
            JSONArray jsonArray = new JSONArray();
            JSONArray protocolList = data.getJSONArray("protocols");
            if (protocolList.size() != 0){
                for (Object o : protocolList) {
                    JSONObject jsonObject1 = new JSONObject();
                    String s = JSONObject.toJSONString(o);
                    JSONObject jsonObject = JSON.parseObject(s);
                    String protocolName = jsonObject.getString("label");
                    String protocolUrl = jsonObject.getString("value");
                    jsonObject1.put("protocalName",protocolName);
                    jsonObject1.put("protocalUrl",protocolUrl);
                    jsonArray.add(jsonObject1);
                }
            }
            infoObject.put("protocalList",jsonArray);
            thirdInfoDTO.setInfoObject(infoObject);

            JSONArray md5List = data.getJSONArray("mobilesMd5");
            String mobileMd5 = memberSourceInfo.getMobileMd5();
            if(MobileMd5IsInListUtils.isMobileMd5InList(md5List,mobileMd5)){
                //如果存在
                pushApiResult.setPushSuccess(false);
                pushApiResult.setCode(code+ "|" + "500");
                pushApiResult.setMessage(msg + "|" + mobileMd5 +"已存在");
                return pushApiResult;
            }

            //进行分润操作
            String priceType = pushApiKeyParam.getPriceType();
            BigDecimal typeRate = pushApiKeyParam.getTypeRate();
            if (ProfitSharingEnum.PROFITPRICE.getValue().equals(priceType)){
                BigDecimal price = data.getBigDecimal("price");//下游返回分润后价格
                if (price.compareTo(new BigDecimal(0.00)) == -1){
                    pushApiResult.setPushSuccess(false);
                    return pushApiResult;
                }
                BigDecimal priceLeft = price.divide(typeRate);//分润前价格
                pushApiResult.setPrice(priceLeft);
                pushApiResult.setPriceRight(price);
            }

            boolean save = merchantThirdBaseInfoService.saveThirdInfo(thirdInfoDTO);
            if (save){
                pushApiResult.setPushSuccess(true);
                pushApiResult.setOutOrderNo(number);
                extJson.put("orderIds", orderId);
            }else{
                pushApiResult.setMessage("保存撞库数据失败");
            }

        }
        return pushApiResult;
    }


    public  String getNumber(){
        SecureRandom secureRandom = new SecureRandom();
        StringBuilder sb = new StringBuilder(16);

        // 第一个字符不为0
        int firstDigit = secureRandom.nextInt(9) + 1;
        sb.append(firstDigit);
        for (int i = 1; i < 16; i++) {
            int digit = secureRandom.nextInt(10);
            sb.append(digit);
        }
        return sb.toString();
    }



    @Override
    public PushApiResult queryApprove(String orderNo, PushApiKeyParam pushApiKeyParam, MemberSourceInfo memberSourceInfo, JSONObject extJson) {
        return null;
    }

    @Override
    public PushApiResult registerUser(String orderNo, String outOrderNo, PushApiKeyParam pushApiKeyParam, MemberSourceInfo memberSourceInfo, JSONObject extJson) throws Exception {
        PushApiResult pushApiResult = new PushApiResult();
        pushApiResult.setPushSuccess(false);
        long timestamp = System.currentTimeMillis();
        String requestUrl = pushApiKeyParam.getRegisterUrl();
        String timestamp1 = String.valueOf(timestamp);
        String apiSecret = pushApiKeyParam.getApiSecret();
        String orderId = extJson.getString("orderIds");
        HashMap<String, Object> paramMap = new HashMap<>();
        paramMap.put("mobile", memberSourceInfo.getMobile());
        paramMap.put("ip", memberSourceInfo.getReqIp());
        paramMap.put("realname", memberSourceInfo.getRealname());
        paramMap.put("device", 1);
        paramMap.put("city",memberSourceInfo.getCity());
        paramMap.put("cityCode",memberSourceInfo.getCityCode());
        paramMap.put("age", memberSourceInfo.getAge());
        paramMap.put("sex", memberSourceInfo.getSex());
        paramMap.put("idCard", memberSourceInfo.getIdcard());
        paramMap.put("province", memberSourceInfo.getProvince());
        paramMap.put("provinceCode", memberSourceInfo.getProvinceCode());
        paramMap.put("loanAmount", memberSourceInfo.getLoanAmount());
        paramMap.put("huaBei", memberSourceInfo.getHuabei());
        paramMap.put("shebao", memberSourceInfo.getShebao());
        paramMap.put("baitiao", memberSourceInfo.getBaitiao());
        paramMap.put("yuqi", memberSourceInfo.getYuqi());
        paramMap.put("house", memberSourceInfo.getHouse());
        paramMap.put("loanTime", memberSourceInfo.getLoanTime());
        paramMap.put("baoxian", memberSourceInfo.getBaoxian());
        paramMap.put("xueli", memberSourceInfo.getXueli());
        paramMap.put("car", memberSourceInfo.getCar());
        paramMap.put("shouru", memberSourceInfo.getShouru());
        paramMap.put("gongzuo", memberSourceInfo.getGongzuo());
        paramMap.put("yongtu", memberSourceInfo.getYongtu());
        paramMap.put("weili", memberSourceInfo.getWeili());
        paramMap.put("xinyongka", memberSourceInfo.getXinyongka());
        paramMap.put("gjj", memberSourceInfo.getGjj());
        paramMap.put("zhima", memberSourceInfo.getZhima());

        String number = getNumber();
        String date = SecureUtil.aes(apiSecret.getBytes()).encryptBase64(JSON.toJSONString(paramMap));
        String s1 = date+"appId="+pushApiKeyParam.getApiCode()+"&nonce="+number+"&timestamp="+timestamp +apiSecret;
        Map<String, Object> aceMap = new HashMap<>();
        aceMap.put("orderId",orderId);
        aceMap.put("data",date);


        SortedMap<String, String> headerMap = new TreeMap<>();
        headerMap.put("Content-Type", "application/json");
        headerMap.put("appId",pushApiKeyParam.getApiCode());
        headerMap.put("timestamp",timestamp1);
        headerMap.put("nonce",number);
        headerMap.put("sign",SecureUtil.md5(s1));

        String requestBody = JSON.toJSONString(aceMap);
        String signatureString = MapUtil.join(paramMap, "&", "=")
                + requestBody
                + MapUtil.join(headerMap, "&", "=")
                + apiSecret;
        headerMap.put("X-Signature", DigestUtil.sha256Hex(signatureString));


        log.info("【金通宝下游】导单开始【queryUrl】{}【bizMap】{}【paramMap】{}", requestUrl, JSON.toJSONString(paramMap), JSON.toJSONString(aceMap));
        String result = HttpUtil.createPost(requestUrl)
                .addHeaders(headerMap)
                .body(requestBody)
                .execute().body();

        JSONObject resultObject = JSON.parseObject(result);


        log.info("【金通宝下游】导单结束【result】{}", resultObject.toJSONString());


        Integer code = resultObject.getInteger("code");
        String msg = resultObject.getString("msg");


        pushApiResult.setCode(code + "|" + msg);
        pushApiResult.setMessage(msg);
        pushApiResult.setParamInfo(JSON.toJSONString(aceMap));
        pushApiResult.setResultInfo(result);

        ThirdInfoDTO thirdInfoDTO = new ThirdInfoDTO();
        thirdInfoDTO.setOrderNo(orderNo);
        thirdInfoDTO.setRetCode(String.valueOf(code));
        thirdInfoDTO.setRetMsg(msg);
        thirdInfoDTO.setResultInfo(result);
        thirdInfoDTO.setStatus("FAILED");

        if (StrUtil.equals(String.valueOf(code), "0") ){
            thirdInfoDTO.setStatus("SUCCESS");
        }
        merchantThirdBaseInfoService.updateThirdInfo(thirdInfoDTO);
        if (StrUtil.equals(String.valueOf(code), "0" )) {
            pushApiResult.setPushSuccess(true);
            pushApiResult.setSettleFlag(true);
            pushApiResult.setStatus(PushStatusEnum.SUCCESS.getValue());
            return pushApiResult;
        }
        pushApiResult.setPushSuccess(false);
        pushApiResult.setSettleFlag(false);
        pushApiResult.setStatus(PushStatusEnum.FAILED.getValue());
        return pushApiResult;
    }


    @Override
    public PushApiResult queryResult(PushQueryParam pushQueryParam, PushApiKeyParam pushApiKeyParam, String extJson) {
        PushApiResult pushApiResult = new PushApiResult();
        pushApiResult.setPushSuccess(false);
        return pushApiResult;
    }

    @Override
    public NoticeParamDTO getNoticeResultParam(String infoId, Map<String, String[]> parameterMap, String paramContent) {
        NoticeParamDTO noticeParamDTO = new NoticeParamDTO();
        return noticeParamDTO;
    }

    @Override
    public JSONObject getNoticeResultReturn(Map<String, String[]> parameterMap, String paramContent, JSONObject extObject) {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("code", 0);
        jsonObject.put("msg", "");
        jsonObject.put("data", "");
        jsonObject.put("flag", true);
        return jsonObject;
    }

    @Override
    public ProtocolParamResult getProtocolResult(MerchantBaseInfo merchantBaseInfo, MemberSourceInfo memberSourceInfo) {
        ProtocolParamResult paramResult = new ProtocolParamResult();
        return paramResult;
    }

    public static String encrypt(String sSrc, String sKey) {
        if (sKey == null) {
            System.out.print("Key 为空 null");
            return null;
        }// 判断 Key 是否为 16 位
        if (sKey.length() != 16) {
            if(sKey.length()!=32){
                System.out.print("Key 不合法");
                return null;
            }
        }
        try {
            byte[] raw = sKey.getBytes("utf-8");
            SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES"); // "算法/模式/补码方式"
            Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
            cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
            byte[] encrypted = cipher.doFinal(sSrc.getBytes("utf-8")); // 此处使用 BASE64 做转码功能，同时能起到 2 次加密的作用。
            return Base64.encodeBase64String(encrypted);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }

}
